/**    
 * @{#} PersonalActivity.java Create on 2014-5-29 下午9:26:48    
 *          
 * @author <a href="mailto:evan0502@qq.com">Evan</a>   
 * @version 1.0    
 */
package com.smiier.skin;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.IntentCompat;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.o.app.json.JsonUtil;
import cn.o.app.media.CropPhotoTask;
import cn.o.app.media.CropPhotoTask.CropPhotoListener;
import cn.o.app.media.PickPhotoTask;
import cn.o.app.media.PickPhotoTask.PickPhotoListener;
import cn.o.app.media.TakePhotoTask;
import cn.o.app.media.TakePhotoTask.TakePhotoListener;
import cn.o.app.net.INetTask;
import cn.o.app.net.NetTaskListener;
import cn.o.app.ui.OActionSheet;
import cn.o.app.ui.OActionSheet.OActionItem;
import cn.o.app.ui.OActionSheet.OnActionItemClickListener;
import cn.o.app.ui.ODatePicker;
import cn.o.app.ui.ODatePicker.OnPickDateListener;
import cn.o.app.ui.OImageView;
import cn.o.app.util.ODateFormat;
import cn.skinapp.R;

import com.evan.common.handler.RequestHandler;
import com.evan.common.handler.callback.HandlerCallback;
import com.evan.common.utils.ImageUtils;
import com.smiier.skin.constant.Constant;
import com.smiier.skin.intercept.RequestTaskIntercept;
import com.smiier.skin.net.UserSetTask;
import com.smiier.skin.net.UserSetTask.UserSetRequest;
import com.smiier.skin.net.UserSetTask.UserSetResponse;
import com.smiier.skin.net.entity.User;
import com.smiier.skin.ui.BasicActivity;
import com.smiier.skin.util.GlobalSettings;
import com.smiier.skin.utils.CommonUtility;
import com.umeng.analytics.MobclickAgent;

public class PatientProfileEditActivity extends BasicActivity {

	private TextView text_patient_name_value, text_patient_id_value,
			text_sex_value, text_birthday_value, text_minzu_value,
			text_address_value, text_job_value, text_marry_value,
			text_huaiyun_value, text_bingshi_value, text_yaowuguomin_value,
			text_putongguominyuan_value, text_jiatingpifubing_value,
			text_mobile_value;

	private OImageView img_patient_icon;

	private boolean isRegisterInit;
	private TextView mSubmit;
	private RelativeLayout rl_huaiyun;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if(CommonUtility.isDoctor()){
			setContentView(R.layout.activity_doctor_edit_profile);
		}else{
		setContentView(R.layout.activity_patient_edit_profile);
		}

		init();

		isRegisterInit = getIntent().getBooleanExtra(Constant.IDENTITY_KEY,
				false);
		View view = findViewById(R.id.show_patient_message);

		mSubmit = (TextView) findViewById(R.id.message_submit);
		if (isRegisterInit) {
			view.setVisibility(View.GONE);
			mSubmit.setVisibility(View.VISIBLE);
			
			setNavRightBtn("跳过");
			setNavTitle("完善个人资料");
			setNavLeftBtnGone();
		} else {
			setNavTitle("个人资料");
			setNavLeftBtn("我的");
		}
		text_patient_name_value = (TextView) findViewById(R.id.text_patient_name_value);
		text_patient_id_value = (TextView) findViewById(R.id.text_patient_id_value);
		text_sex_value = (TextView) findViewById(R.id.text_sex_value);
		text_birthday_value = (TextView) findViewById(R.id.text_birthday_value);
		text_minzu_value = (TextView) findViewById(R.id.text_minzu_value);
		text_address_value = (TextView) findViewById(R.id.text_address_value);
		text_job_value = (TextView) findViewById(R.id.text_job_value);
		text_marry_value = (TextView) findViewById(R.id.text_marry_value);
		text_huaiyun_value = (TextView) findViewById(R.id.text_huaiyun_value);
		text_bingshi_value = (TextView) findViewById(R.id.text_bingshi_value);
		text_yaowuguomin_value = (TextView) findViewById(R.id.text_yaowuguomin_value);
		text_putongguominyuan_value = (TextView) findViewById(R.id.text_putongguominyuan_value);
		text_jiatingpifubing_value = (TextView) findViewById(R.id.text_jiatingpifubing_value);
		text_mobile_value = (TextView) findViewById(R.id.text_mobile_value);
		img_patient_icon = (OImageView) findViewById(R.id.img_patient_icon);
		try {
			String path = GlobalSettings.sUser.Pic;
			if (!CommonUtility.isNull(path)) {
				// mBitmapUtils.display(img_patient_icon,
				// GlobalSettings.SERVER_IMG_URL
				// + GlobalSettings.sUser.Pic + Constant.IMG_SRC,
				// new OBitmapLoadCallBack<View>());
				CommonUtility.displayHeadImage(img_patient_icon, mBitmapUtils,
						GlobalSettings.SERVER_IMG_URL
								+ GlobalSettings.sUser.Pic + Constant.IMG_SRC,
						getResources(), GlobalSettings.sUser.Sex);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		rl_huaiyun = (RelativeLayout) findViewById(R.id.rl_huaiyun);
	}

	@Override
	protected void onResume() {
		super.onResume();
		
//		MobclickAgent.onResume(this);
		
		try {
			text_patient_name_value.setText(GlobalSettings.sUser.Name);
			text_patient_id_value.setText(GlobalSettings.sUser.Nick);
			text_mobile_value.setText(GlobalSettings.sUser.Mobile);
			int sex = GlobalSettings.sUser.Sex;
			text_sex_value.setText(CommonUtility.sex.get(sex));
			if (sex == 0) {
				rl_huaiyun.setVisibility(View.GONE);
			} else {
				// rl_huaiyun.setVisibility(View.VISIBLE);
				text_huaiyun_value.setText(CommonUtility.huaiyun
						.get(GlobalSettings.sUser.Pregnant_Status));
			}

			String date = CommonUtility.formatDate(
					GlobalSettings.sUser.Birth.toString(), 0, 10);
			if (date.equals("0001-01-01")) {
				text_birthday_value.setVisibility(View.INVISIBLE);
			} else {
				text_birthday_value.setVisibility(View.VISIBLE);
				text_birthday_value.setText(date);
			}

			text_minzu_value.setText(GlobalSettings.sUser.Nation);
			StringBuilder address = new StringBuilder();
			address.append(GlobalSettings.sUser.Province)
					.append(GlobalSettings.sUser.City)
					.append(GlobalSettings.sUser.County);
			text_address_value.setText(address);
			text_job_value.setText(GlobalSettings.sUser.Job);
			text_marry_value.setText(CommonUtility.marry
					.get(GlobalSettings.sUser.Marital_Status));
			text_bingshi_value
					.setText(CommonUtility.convertJSONArray2String(
							new JSONArray(
									JsonUtil.convert(GlobalSettings.sUser.MedicalHistory)),
							","));
			text_yaowuguomin_value
					.setText(CommonUtility.convertJSONArray2String(
							new JSONArray(JsonUtil
									.convert(GlobalSettings.sUser.DrugAllergen)),
							","));
			text_putongguominyuan_value.setText(CommonUtility
					.convertJSONArray2String(
							new JSONArray(JsonUtil
									.convert(GlobalSettings.sUser.Allergen)),
							","));
			text_jiatingpifubing_value
					.setText(CommonUtility.convertJSONArray2String(
							new JSONArray(
									JsonUtil.convert(GlobalSettings.sUser.FamilyMedicalHistory)),
							","));

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void onClick(View view) {
		super.onClick(view);
		Intent intent = null;
		int id = view.getId();
		if (id == R.id.text_patient_icon) {
			onClickUserIcon();
		} else if (id == R.id.text_patient_name) {
			intent = new Intent(activity, UpdateInfoInputActivity.class);
			intent.putExtra(Constant.IDENTITY_KEY_PARAM_KEY, "Name");
			intent.putExtra(Constant.IDENTITY_KEY_NAV_TITLE, "更改姓名");
			startActivity(intent);
		} else if (id == R.id.text_patient_id) {
			intent = new Intent(activity, UpdateInfoInputActivity.class);
			intent.putExtra(Constant.IDENTITY_KEY_PARAM_KEY, "Nick");
			intent.putExtra(Constant.IDENTITY_KEY_NAV_TITLE, "更改皮肤科ID");
			startActivity(intent);
		} else if (id == R.id.text_mobile) {
			intent = new Intent(activity, RegisterFirstStepActivity.class);
			intent.putExtra(Constant.IDENTITY_KEY_1,
					Constant.TYPE_UPDATE_MOBILE);
			startActivity(intent);
		} else if (id == R.id.text_sex) {
			intent = new Intent(activity, CommonDataChooseActivity.class);
			String[] datas = { "[\"男\",\"女\"]", "修改性别", "Sex",
					CommonDataChooseActivity.TYPE_FIXATION,
					CommonDataChooseActivity.SINGLECHOOSE,
					CommonDataChooseActivity.DATA_TYPE_SEX };
			intent.putExtra(Constant.IDENTITY_KEY, datas);
			startActivity(intent);
		} else if (id == R.id.text_birthday) {
			ODatePicker datePicker = new ODatePicker(getContext());
			datePicker.show();
			datePicker.setListener(new OnPickDateListener() {

				@Override
				public void onPicked(ODatePicker picker, Date d, String time) {
					String date = ODateFormat.format(d, "yyyy-MM-dd");
					text_birthday_value.setText(date);
					if (!CommonUtility.isNull(date)) {
						HashMap<String, Object> params = new HashMap<String, Object>();
						params.put("Birth", date);
						params.put(Constant.PARAM_API, "User.Set");
						params.put(Constant.PARAM_TOKEN, GlobalSettings.sToken);
						RequestTaskIntercept.requestIntercept(activity,
								Constant.URL.REQUEST, new RequestHandler(
										activity, new HandlerCallback() {

											@Override
											public void callback(Object o) {
												if (!CommonUtility.isNull(o)) {
													JSONObject object = (JSONObject) o;
													if (CommonUtility
															.response200(object)) {
														text_birthday_value
																.setVisibility(View.VISIBLE);
														CommonUtility.toast(
																activity,
																"保存成功");
														try {
															GlobalSettings.sUser = JsonUtil
																	.convertFromObject(
																			object.getJSONObject("Res"),
																			User.class);
														} catch (Exception e) {
															e.printStackTrace();
														}
													} else {
														CommonUtility.toast(
																activity,
																"保存失败");
													}
												}
											}
										}), params);
					}
				}
			});
		} else if (id == R.id.text_minzu) {
			intent = new Intent(activity, CommonDataChooseActivity.class);
			String[] datas = { Constant.URL.REQUEST_NATION_JSON, "修改民族",
					"Nation", CommonDataChooseActivity.TYPE_URL,
					CommonDataChooseActivity.SINGLECHOOSE, "" };
			intent.putExtra(Constant.IDENTITY_KEY, datas);
			startActivity(intent);
		} else if (id == R.id.text_address) {
			intent = new Intent(activity, MulitLevelDataChooseActivity.class);
			String[] datas = {
					Constant.URL.REQUEST_AREA_JSON,
					"选择省份",
					"Province" + Constant.SPLIT + "City" + Constant.SPLIT
							+ "County" };
			intent.putExtra(Constant.IDENTITY_KEY, datas);
			startActivity(intent);
		} else if (id == R.id.text_job) {
			intent = new Intent(activity, MulitLevelDataChooseActivity.class);
			String[] datas = { Constant.URL.REQUEST_JOBS_JSON, "选择行业", "Job" };
			intent.putExtra(Constant.IDENTITY_KEY, datas);
			intent.putExtra(Constant.IDENTITY_KEY_LEVEL_2,
					Constant.IDENTITY_KEY_LEVEL_2);
			// intent = new Intent(activity, JobsActivity.class);
			startActivity(intent);
		} else if (id == R.id.text_marry) {
			intent = new Intent(activity, CommonDataChooseActivity.class);
			String[] datas = { "[\"未婚\",\"已婚\"]", "修改婚姻状况", "Marital_Status",
					CommonDataChooseActivity.TYPE_FIXATION,
					CommonDataChooseActivity.SINGLECHOOSE,
					CommonDataChooseActivity.DATA_TYPE_MARRY };
			intent.putExtra(Constant.IDENTITY_KEY, datas);
			startActivity(intent);
		} else if (id == R.id.text_huaiyun) {
			intent = new Intent(activity, CommonDataChooseActivity.class);
			String[] datas = { "[\"未孕\",\"怀孕\"]", "修改怀孕状况", "Pregnant_Status",
					CommonDataChooseActivity.TYPE_FIXATION,
					CommonDataChooseActivity.SINGLECHOOSE,
					CommonDataChooseActivity.DATA_TYPE_HUAIYUN };
			intent.putExtra(Constant.IDENTITY_KEY, datas);
			startActivity(intent);
		} else if (id == R.id.text_bingshi) {
			intent = new Intent(activity, CommonDataChooseActivity.class);
			String[] datas = { Constant.URL.REQUEST_MEDICALHISTORY_JSON,
					"修改病史", "MedicalHistory",
					CommonDataChooseActivity.TYPE_URL,
					CommonDataChooseActivity.MULITCHOOSE, "" };
			intent.putExtra(Constant.IDENTITY_KEY, datas);
			startActivity(intent);
		} else if (id == R.id.text_yaowuguomin) {
			intent = new Intent(activity, CommonDataChooseActivity.class);
			String[] datas = { Constant.URL.REQUEST_DRUGALLERGEN_JSON,
					"修改药物过敏", "DrugAllergen",
					CommonDataChooseActivity.TYPE_URL,
					CommonDataChooseActivity.MULITCHOOSE, "" };
			intent.putExtra(Constant.IDENTITY_KEY, datas);
			startActivity(intent);
		} else if (id == R.id.text_putongguominyuan) {
			intent = new Intent(activity, CommonDataChooseActivity.class);
			String[] datas = { Constant.URL.REQUEST_ALLERGEN_JSON, "修改普通过敏源",
					"Allergen", CommonDataChooseActivity.TYPE_URL,
					CommonDataChooseActivity.MULITCHOOSE, "" };
			intent.putExtra(Constant.IDENTITY_KEY, datas);
			startActivity(intent);
		} else if (id == R.id.text_jiarenpifubing) {
			intent = new Intent(activity, CommonDataChooseActivity.class);
			String[] datas = { Constant.URL.REQUEST_DISEASE_JSON, "修改家人皮肤病情况",
					"FamilyMedicalHistory", CommonDataChooseActivity.TYPE_URL,
					CommonDataChooseActivity.MULITCHOOSE, "" };
			intent.putExtra(Constant.IDENTITY_KEY, datas);
			startActivity(intent);
		} else if (id == R.id.text_right) {
			intent = new Intent(this, GlobalSettings.getActivity4Navigate(this));
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
					| IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
			startActivity(intent);
		} else if (id == R.id.message_submit) {
			
			if(GlobalSettings.sUser != null){
				UserSetTask task = new UserSetTask();
				UserSetRequest req = new UserSetRequest();
				req.token = GlobalSettings.sToken;
				req.Name = GlobalSettings.sUser.Name;
				task.setRequest(req);
				task.addListener(new NetTaskListener<UserSetTask.UserSetRequest, UserSetTask.UserSetResponse>() {

					@Override
					public void onException(
							INetTask<UserSetRequest, UserSetResponse> task,
							Exception e) {

					}

					@Override
					public void onComplete(
							INetTask<UserSetRequest, UserSetResponse> task,
							UserSetResponse response) {
						if (!CommonUtility.isNull(response)
								&& response.ResultCode == 200) {
							Toast.makeText(PatientProfileEditActivity.this, "保存成功",
									Toast.LENGTH_SHORT).show();
							Intent intent = new Intent(
									PatientProfileEditActivity.this,
									GlobalSettings
											.getActivity4Navigate(PatientProfileEditActivity.this));
							intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
									| IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
							startActivity(intent);
						} else {
							Toast.makeText(PatientProfileEditActivity.this, "保存失败",
									Toast.LENGTH_SHORT).show();
						}
					}
				});
				add(task);
			}else{
				
				intent = new Intent(this, GlobalSettings.getActivity4Navigate(this));
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
						| IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
				startActivity(intent);
				
			}
			
			

		}
	}

	protected void onClickUserIcon() {
		ArrayList<OActionItem> dataProvider = new ArrayList<OActionSheet.OActionItem>();
		OActionItem item = null;
		item = new OActionItem();
		item.setText("拍照");
		dataProvider.add(item);
		item = new OActionItem();
		item.setText("从手机相册选择");
		dataProvider.add(item);
		OActionSheet<OActionItem> actionSheet = new OActionSheet<OActionSheet.OActionItem>(
				this);
		actionSheet.setCancel("取消");
		actionSheet.setDataProvider(dataProvider);
		actionSheet.show(false, true);
		actionSheet
				.setOnActionItemClickListener(new OnActionItemClickListener<OActionSheet.OActionItem>() {

					@Override
					public void onItemClick(OActionSheet<OActionItem> sheet,
							View v, int position, OActionItem dataItem) {
						if (position == 0) {
							TakePhotoTask task = new TakePhotoTask(
									PatientProfileEditActivity.this,
									GlobalSettings.REQUEST_CODE_TAKE_PHOTO);
							task.takePhoto();
							task.setListener(new TakePhotoListener() {

								@Override
								public void onComplete(Uri uri) {
									CropPhotoTask task = new CropPhotoTask(
											PatientProfileEditActivity.this,
											GlobalSettings.REQUEST_CODE_CROP_PHOTO);
									task.cropPhoto(uri, 150, 150);
									task.setListener(new CropPhotoListener() {

										@Override
										public void onComplete(Uri uri) {
											uploadPic(uri.getPath());
										}
									});
								}
							});
						}
						if (position == 1) {
							PickPhotoTask task = new PickPhotoTask(
									PatientProfileEditActivity.this,
									GlobalSettings.REQUEST_CODE_PICK_PHOTO);
							task.pickPhoto();
							task.setListener(new PickPhotoListener() {

								@Override
								public void onComplete(Uri uri) {
									CropPhotoTask task = new CropPhotoTask(
											PatientProfileEditActivity.this,
											GlobalSettings.REQUEST_CODE_CROP_PHOTO);
									task.cropPhoto(uri, 150, 150);
									task.setListener(new CropPhotoListener() {

										@Override
										public void onComplete(Uri uri) {
											uploadPic(uri.getPath());
										}
									});
								}
							});
						}
					}
				});
	}

	protected void uploadPic(String path) {
		File f = new File(path);
		if (f.exists()) {
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put(Constant.PARAM_TOKEN, GlobalSettings.sToken);
			params.put("pic", f);
			params.put(Constant.PARAM_API, "SYS.UploadPic");
			RequestTaskIntercept.requestIntercept(activity,
					Constant.URL.REQUEST, new RequestHandler(activity,
							new HandlerCallback() {
								@Override
								public void callback(Object o) {
									if (!CommonUtility.isNull(o)) {
										try {
											JSONObject object = (JSONObject) o;
											if (CommonUtility
													.response200(object)) {
												final String path = object
														.getString(Constant.JSON_PARAM_RES);
												HashMap<String, Object> params_ = new HashMap<String, Object>();
												params_.put(
														Constant.PARAM_TOKEN,
														GlobalSettings.sToken);
												params_.put("Pic", path);
												params_.put(Constant.PARAM_API,
														"User.Set");
												RequestTaskIntercept
														.requestIntercept(
																activity,
																Constant.URL.REQUEST,
																new RequestHandler(
																		activity,
																		new HandlerCallback() {

																			@Override
																			public void callback(
																					Object o) {
																				if (!CommonUtility
																						.isNull(o)) {
																					JSONObject object = (JSONObject) o;
																					if (CommonUtility
																							.response200(object)) {
																						try {
																							GlobalSettings.sUser.Pic = path;
																						} catch (Exception e) {
																							e.printStackTrace();
																						}
																					}
																				}
																			}
																		}),
																params_);
											}
										} catch (Exception e) {
											e.printStackTrace();
										}
									}

								}
							}), params);
			Bitmap bitmap = ImageUtils
					.getRoundCornerBitMap(f.getAbsolutePath());
			img_patient_icon.setImageBitmap(bitmap);
		}
	}

	@Override
	public void onBackPressed() {
		if (!isRegisterInit) {
			finish();
		}
	}

/*	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(getContext());
	}*/
}
